//
//  PHRegisterViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/12/20.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHRegisterViewController.h"

@interface PHRegisterViewController ()<QMUINavigationControllerDelegate, QMUITextFieldDelegate>
@property(nonatomic, strong) QMUITextField *nameTextField;
@property(nonatomic, strong) QMUITextField *codeTextField;
@property(nonatomic, strong) QMUIButton *codeBtn;
@property(nonatomic, strong) QMUITextField *pwdTextField1;
@property(nonatomic, strong) QMUITextField *pwdTextField2;
@property(nonatomic, strong) QMUIFillButton *registerBtn;

@property(nonatomic, strong) QMUIButton *checkBtn;
@property(nonatomic, strong) QMUILabel *readLabel;
@property(nonatomic, strong) QMUIButton *protocolBtn;

@property(nonatomic, strong) KKTimer *timer;

@property(nonatomic, assign) PHMethod method;
@end

@implementation PHRegisterViewController

- (instancetype)initWithMethod:(PHMethod)method
{
    self = [super init];
    if (self) {
        _method = method;
    }
    return self;
}

- (void)initSubviews {
    [super initSubviews];
    
    _nameTextField = [[QMUITextField alloc] init];
    _nameTextField.borderStyle = UITextBorderStyleNone;
    _nameTextField.returnKeyType = UIReturnKeyDone;
    _nameTextField.backgroundColor = UIColorClear;
    _nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTextField.font = CodeFontMake(14);
    _nameTextField.textColor = UIColorBlack;
    _nameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameTextField.placeholder = NSLocalizedString(@"tips_input_username", nil);
    _nameTextField.delegate = self;
    _nameTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _nameTextField.enablesReturnKeyAutomatically = YES;
//    [_nameTextField addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_nameTextField];
    
    UIImageView *nameIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    nameIV.image = UIImageMake(@"login_user");
    _nameTextField.leftViewMode = UITextFieldViewModeAlways;
    _nameTextField.leftView = nameIV;
    
    
    _codeTextField = [[QMUITextField alloc] init];
    _codeTextField.borderStyle = UITextBorderStyleNone;
    _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    _codeTextField.returnKeyType = UIReturnKeyDone;
    _codeTextField.backgroundColor = UIColorClear;
    _codeTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _codeTextField.font = CodeFontMake(14);
    _codeTextField.textColor = UIColorBlack;
    _codeTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _codeTextField.placeholder = NSLocalizedString(@"tips_input_code", nil);
    _codeTextField.delegate = self;
    _codeTextField.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _codeTextField.enablesReturnKeyAutomatically = YES;
//    [_codeTextField addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_codeTextField];
    
    UIImageView *codeIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    codeIV.image = UIImageMake(@"login_code");
    _codeTextField.leftViewMode = UITextFieldViewModeAlways;
    _codeTextField.leftView = codeIV;
    
    _codeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 120, 30)];
    _codeBtn.titleLabel.font = CodeFontMake(12);
    _codeBtn.titleLabel.numberOfLines = 0;
    [_codeBtn setTitle:NSLocalizedString(@"btn_get_verify_code", nil) forState:UIControlStateNormal];
    [_codeBtn addTarget:self action:@selector(codeAction:) forControlEvents:UIControlEventTouchUpInside];
    _codeBtn.qmui_borderPosition = QMUIBorderViewPositionLeft;
    _codeTextField.rightViewMode = UITextFieldViewModeAlways;
    _codeTextField.rightView = _codeBtn;
    
    CALayer *line = [QDCommonUI generateSeparatorLayer];
    line.frame = CGRectMake(0, 0, PixelOne, 30);
    [_codeBtn.layer addSublayer:line];
    
    if (_method != PHMethodBindWechat) {
        _pwdTextField1 = [[QMUITextField alloc] init];
        _pwdTextField1.borderStyle = UITextBorderStyleNone;
        _pwdTextField1.returnKeyType = UIReturnKeyDone;
        _pwdTextField1.backgroundColor = UIColorClear;
        _pwdTextField1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _pwdTextField1.font = CodeFontMake(14);
        _pwdTextField1.textColor = UIColorBlack;
        _pwdTextField1.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _pwdTextField1.clearButtonMode = UITextFieldViewModeWhileEditing;
        _pwdTextField1.placeholder = NSLocalizedString(@"tips_input_password", nil);
        _pwdTextField1.secureTextEntry = YES;
        _pwdTextField1.delegate = self;
        _pwdTextField1.qmui_borderPosition = QMUIBorderViewPositionBottom;
        _pwdTextField1.enablesReturnKeyAutomatically = YES;
//        [_pwdTextField1 addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:_pwdTextField1];
        
        UIImageView *pwdIV1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        pwdIV1.image = UIImageMake(@"login_pwd");
        _pwdTextField1.leftViewMode = UITextFieldViewModeAlways;
        _pwdTextField1.leftView = pwdIV1;
        
        
        _pwdTextField2 = [[QMUITextField alloc] init];
        _pwdTextField2.borderStyle = UITextBorderStyleNone;
        _pwdTextField2.returnKeyType = UIReturnKeyDone;
        _pwdTextField2.backgroundColor = UIColorClear;
        _pwdTextField2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _pwdTextField2.font = CodeFontMake(14);
        _pwdTextField2.textColor = UIColorBlack;
        _pwdTextField2.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _pwdTextField2.clearButtonMode = UITextFieldViewModeWhileEditing;
        _pwdTextField2.placeholder = NSLocalizedString(@"tips_input_password_again", nil);
        _pwdTextField2.secureTextEntry = YES;
        _pwdTextField2.delegate = self;
        _pwdTextField2.qmui_borderPosition = QMUIBorderViewPositionBottom;
        _pwdTextField2.enablesReturnKeyAutomatically = YES;
//        [_pwdTextField2 addTarget:self action:@selector(updateSubmitButtonEnables) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:_pwdTextField2];
        
        UIImageView *pwdIV2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        pwdIV2.image = UIImageMake(@"login_pwd");
        _pwdTextField2.leftViewMode = UITextFieldViewModeAlways;
        _pwdTextField2.leftView = pwdIV2;
    }
    /*
    _checkBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_checkBtn setImage:[QMUIHelper imageWithName:@"QMUI_pickerImage_checkbox"] forState:UIControlStateNormal];
    [_checkBtn setImage:[QMUIHelper imageWithName:@"QMUI_pickerImage_checkbox_checked"] forState:UIControlStateSelected];
    [_checkBtn setImage:[QMUIHelper imageWithName:@"QMUI_pickerImage_checkbox_checked"] forState:UIControlStateHighlighted];
    [_checkBtn addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_checkBtn];
    [_checkBtn setSelected:YES];
    
    _readLabel = [[QMUILabel alloc] init];
    _readLabel.font = CodeFontMake(14);
    _readLabel.textColor = UIColorGray5;
    _readLabel.text = NSLocalizedString(@"tips_read_approval", nil);
    [self.view addSubview:_readLabel];
    
    _protocolBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    _protocolBtn.titleLabel.font = CodeFontMake(14);
    _protocolBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_protocolBtn setTitleColor:UIColorBlue forState:UIControlStateNormal];
    [_protocolBtn setTitle:NSLocalizedString(@"phnix_service_protocol", nil) forState:UIControlStateNormal];
    [_protocolBtn addTarget:self action:@selector(protocolAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_protocolBtn];
    */
    
    _registerBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorRed];
    _registerBtn.titleLabel.font = CodeFontMake(16);
    if (_method == PHMethodBindWechat) {
        [_registerBtn setTitle:NSLocalizedString(@"btn_ok", nil) forState:UIControlStateNormal];
    }
    else if (_method == PHMethodForgetPWD) {
        [_registerBtn setTitle:NSLocalizedString(@"btn_reset_password", nil) forState:UIControlStateNormal];
    }
    else {
        [_registerBtn setTitle:NSLocalizedString(@"btn_sign_up", nil) forState:UIControlStateNormal];
    }
    [_registerBtn addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _nameTextField.frame = CGRectMake(30.0f, self.qmui_navigationBarMaxYInViewCoordinator + 20, SCREEN_WIDTH - 2 * 30.0f, 40);
    _codeTextField.frame = CGRectMake(_nameTextField.qmui_left, _nameTextField.qmui_bottom + 10, _nameTextField.qmui_width, _nameTextField.qmui_height);
    
    CGFloat yoffset = _codeTextField.qmui_bottom + 20;
    if (_method != PHMethodBindWechat) {
        _pwdTextField1.frame = CGRectMake(_nameTextField.qmui_left, _codeTextField.qmui_bottom + 10, _nameTextField.qmui_width, _nameTextField.qmui_height);
        _pwdTextField2.frame = CGRectMake(_nameTextField.qmui_left, _pwdTextField1.qmui_bottom + 10, _nameTextField.qmui_width, _nameTextField.qmui_height);
        yoffset = _pwdTextField2.qmui_bottom + 20;
    }
    
    /*
    _checkBtn.frame = CGRectMake(_nameTextField.qmui_left, _pwdTextField2.qmui_bottom + 20, 20, 20);
    _readLabel.frame = CGRectMake(_checkBtn.qmui_right, _checkBtn.qmui_top + 2, 200, 16);
    [_readLabel sizeToFit];
    _protocolBtn.frame = CGRectMake(_readLabel.qmui_right, _checkBtn.qmui_top, _nameTextField.qmui_width - _readLabel.qmui_right, 20);
    
    _registerBtn.frame = CGRectMake(_nameTextField.qmui_left, _checkBtn.qmui_bottom + 10, _nameTextField.qmui_width, 40);
    */
    
    _registerBtn.frame = CGRectMake(_nameTextField.qmui_left, yoffset, _nameTextField.qmui_width, 40);
}

-(void)codeAction:(QMUIButton *)sender {
    NSString *user = _nameTextField.text;
    if ([NSString dd_checkMobileNumber:user] || [NSString dd_checkEmail:user]) {
        WS(ws);
        NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"tips_send_verify_code", nil), user];
        [KKAlert alertWithTitle:NSLocalizedString(@"btn_get_verify_code", nil) message:msg cancel:^{
            
        } ok:^{
            [ws checkUser:user];
//            [ws getCodeWithUser:user];
        }];
    } else {
        [KKHUD showError:NSLocalizedString(@"tips_username_invalid", nil)];
    }
}

-(void)checkUser:(NSString *)user {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if ([NSString dd_checkMobileNumber:user]) {
        [parameters setObject:user forKey:@"phone"];
    } else if ([NSString dd_checkEmail:user]) {
        [parameters setObject:user forKey:@"email"];
    }
    LOG(@"parameters %@",parameters);
    
    WS(ws);
    [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    [[NetUtils JSONManager] POST:@"user/checkUserIsHad.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        BOOL exist = result.error_code == -1;
        if (ws.method == PHMethodForgetPWD) {
            if (exist) {
                [ws getCodeWithUser:user];
            } else {
                [KKHUD showError:NSLocalizedString(@"tips_user_not_exist", nil)];
            }
        } else if (ws.method == PHMethodRegister) {
            if (!exist) {
                [ws getCodeWithUser:user];
            } else {
                [KKHUD showError:NSLocalizedString(@"tips_user_exist", nil)];
            }
        } else {
            [ws getCodeWithUser:user];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

-(void)getCodeWithUser:(NSString *)user {
    WS(ws);
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if ([NSString dd_checkMobileNumber:user]) {
        [parameters setObject:user forKey:@"phone"];
    } else if ([NSString dd_checkEmail:user]) {
        [parameters setObject:user forKey:@"email"];
    }
    LOG(@"parameters %@",parameters);
    
    [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    [[NetUtils JSONManager] POST:@"user/getCode.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        if (result && result.is_result_suc) {
            [KKHUD showSucceed:NSLocalizedString(@"tips_success", nil)];
            
            ws.codeBtn.enabled = NO;
            [ws.codeTextField becomeFirstResponder];
            ws.timer = [KKTimer every:1.0 repeat:60 task:^(NSUInteger times) {
                if (times == 60) {
                    [ws.codeBtn setTitle:NSLocalizedString(@"btn_get_verify_code", nil) forState:UIControlStateNormal];
                    ws.codeBtn.enabled = YES;
                } else {
                    NSString *title = [NSString stringWithFormat:@"%ds", 60 - (int)times];
                    [ws.codeBtn setTitle:title forState:UIControlStateNormal];
                }
            }];
        } else {
            [KKHUD showError:result.error_msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

-(void)registerAction:(id)sender {
    NSString *username = _nameTextField.text;
    NSString *code = _codeTextField.text;
    
//    if (!_checkBtn.isSelected) {
//        [KKHUD showError:NSLocalizedString(@"tips_protocol_not_checked", nil)];
//        return;
//    }
    if (![NSString dd_checkMobileNumber:username] && ![NSString dd_checkEmail:username]) {
        [KKAlert warningWithText:NSLocalizedString(@"tips_check_username", nil)];
        return;
    }
    if (![NSString dd_checkValidateCode:code]) {
        [KKAlert warningWithText:NSLocalizedString(@"tips_check_code", nil)];
        return;
    }
    
    if (_method == PHMethodBindWechat) {
        [NetUtils registerWithType:PHAccountTypeWechat name:username code:code third_id:_third_id password:nil];
    } else {
        NSString *password = _pwdTextField1.text;
        if (![NSString dd_checkPassword:password]) {
            [KKAlert warningWithText:NSLocalizedString(@"tips_check_password", nil)];
            return;
        }
        if (![password isEqualToString:_pwdTextField2.text]) {
            [KKAlert warningWithText:NSLocalizedString(@"tips_password_not_same", nil)];
            return;
        }
        
        PHAccountType type = [NetUtils typeWithName:username];
        if (_method == PHMethodForgetPWD) {
            [NetUtils findPasswordWithType:type name:username code:code password:password];
        } else {
            [NetUtils registerWithType:type name:username code:code third_id:nil password:password];
        }
    }
}

-(void)checkAction:(QMUIButton *)sender {
    sender.selected = !sender.isSelected;
}

-(void)protocolAction:(id)sender {
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
//    [self updateSubmitButtonEnables];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (_timer && _timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)updateSubmitButtonEnables {
    BOOL result = ([NSString dd_checkMobileNumber:_nameTextField.text] || [NSString dd_checkEmail:_nameTextField.text]) && [NSString dd_checkValidateCode:_codeTextField.text];
    if (_method != PHMethodBindWechat) {
        result = result && [NSString dd_checkPassword:_pwdTextField1.text] && [NSString dd_checkPassword:_pwdTextField2.text];
    }
    self.registerBtn.enabled = result;
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    if (_method == PHMethodBindWechat) {
        self.title = NSLocalizedString(@"title_bind_wechat", nil);
    }
    else if (_method == PHMethodForgetPWD) {
        self.title = NSLocalizedString(@"title_find_password", nil);
    }
    else {
        self.title = NSLocalizedString(@"title_register_user", nil);
    }
}

#pragma mark - QMUINavigationControllerDelegate
- (BOOL)shouldSetStatusBarStyleLight {
    return YES;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
